<!-- 老师（管理员）回复学生（普通用户）留言页面 -->
<script setup lang="ts">
import { useUserInfoStore } from '@/store/userInfo'
import { fetchManagerMessageListAPI } from '@/apis/fetchManagerMessageList'
import { managerSendMessageAPI } from '@/apis/managerSendMessage'

const userInfoStore = useUserInfoStore()

/* ------------------------------- 业务数据 START ------------------------------- */
// 会话 id，用于获取留言（聊天）对话数据
const chatId = ref('')

// 班级 id，用户提交留言
const classId = ref('')
// 学生 id，用于提交留言
const studentId = ref('')

// 消息列表数据
const dataList = ref<Message[]>([])
/* -------------------------------- 业务数据 END -------------------------------- */

/* ------------------------------- 视图数据 START ------------------------------- */
// 滚动组件 ref
const paging = ref<any>(null)
// 输入框到输入法区域的距离
const inputBarCursorSpacing = uni.upx2px(40)
// 输入框文本
const inputText = ref('')
/* -------------------------------- 视图数据 END -------------------------------- */

onLoad(async (options) => {
  if (options
    && options.chat_id
    && options.class_id
    && options.student_id
    && options.username) {
    chatId.value = options.chat_id
    classId.value = options.class_id
    studentId.value = options.student_id
    uni.setNavigationBarTitle({ title: options.username })
  }
  else {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
  }
})

/**
 * @description 由滚动视图组件调用的分页处理函数
 */
async function queryList(pageNo: any) {
  try {
    const res = await fetchManagerMessageListAPI({
      id: chatId.value,
      page: pageNo,
      limit: '50',
    }, userInfoStore.userInfo!.token!)

    if (res.data?.code === 1)
      paging.value.complete(res.data?.data.data)
    else
      paging.value.complete(false)
  }
  catch {
    paging.value.complete(false)
  }
}

/**
 * @description 点击聊天气泡时触发，收起键盘
 */
function handleTouchCell() {
  uni.hideKeyboard()
}

/**
 * @description 点击“发送”按钮时触发
 */
async function handleSend() {
  try {
    uni.showLoading({ title: '发送中...' })

    const res = await managerSendMessageAPI({
      content: inputText.value,
      classes_id: classId.value,
      recover_user_id: studentId.value,
    }, userInfoStore.userInfo!.token!)

    if (res.data?.code === 1) {
      const newMsgRes = await fetchManagerMessageListAPI({
        id: chatId.value,
        page: '1',
        limit: '50',
      }, userInfoStore.userInfo!.token!)

      if (newMsgRes.data?.code === 1) {
        paging.value.addChatRecordData(newMsgRes.data.data.data[0])
        inputText.value = ''
        uni.hideLoading()
      }
      else {
        uni.showToast({ title: newMsgRes.data?.msg, icon: 'none' })
        uni.hideLoading()
      }
    }
    else {
      uni.showToast({ title: res.data?.msg, icon: 'none' })
      uni.hideLoading()
    }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}
</script>

<template>
  <view class="min-h-screen bg-#F8FAFE">
    <!-- 滚动视图组件 -->
    <z-paging
      ref="paging"
      v-model="dataList"
      use-chat-record-mode
      safe-area-inset-bottom
      bottom-bg-color="#ffffff"
      @query="queryList"
    >
      <cell
        v-for="message in dataList"
        :key="message.id"
        @touchstart="handleTouchCell"
      >
        <ChatBubble
          :avatar="message.avatar"
          :direction="message.user_id.toString() === userInfoStore.userInfo?.user_id.toString() ? 'toLeft' : 'toRight'"
          :content="message.content"
        />
      </cell>

      <!-- 下方输入框 -->
      <template #bottom>
        <view
          class="w-screen flex items-center rounded-t-40rpx bg-white px-25rpx py-20rpx transition-all duration-300 ease-in-out"
        >
          <input
            v-model="inputText"
            type="text"
            class="h-80rpx w-524rpx rounded-20rpx bg-#F4F4F4 px-25rpx text-24rpx text-#333333 leading-32rpx"
            :adjust-position="false"
            :cursor-spacing="inputBarCursorSpacing"
            hold-keyboard
            placeholder="请输入您的交流内容"
            placeholder-class="text-#919191"
          >
          <Spacer width="16" />
          <button
            class="h-80rpx w-160rpx flex items-center justify-center rounded-20rpx bg-#0037AE text-28rpx text-white font-semibold leading-40rpx"
            hover-class="bg-#3266D9"
            @tap="handleSend"
          >
            发送
          </button>
        </view>
      </template>
    </z-paging>
  </view>
</template>

<route lang="yaml">
name: 'managerChat'
style:
  disableScroll: true
</route>
